package org.bocs.untils;

import io.jsonwebtoken.*;
import java.util.Date;
import java.util.HashMap;

public class JwtHelper {
    // 随机字符串混淆Token
    private static final String tokenSignKey = "uNvSpMOneTimeInEachNavigationGuardNvSpMOneTimeInEachNavigationGuard";
    /**
     * 生成Token，并保存userID和userName信息
     * @param userId
     * @param userName
     * @return
     */
    public static String createToken(Integer userId, String userName) {
        long tokenExpiration = 1000L * 60 * 60 * 24 * 30; // 过期时间，设置30天
        JwtBuilder builder = Jwts.builder();
        HashMap<String, Object> map = new HashMap<>();
        String jwt = builder
                .setExpiration(new Date(System.currentTimeMillis() + tokenExpiration))
                .setIssuedAt(new Date())
                .setId(userId + "")
                .setSubject(userName)
                .setClaims(map)
                .signWith(SignatureAlgorithm.HS256, tokenSignKey)
                .compressWith(CompressionCodecs.GZIP)
                .compact();
        return "Bearer " + jwt;
    }

    /**
     * 查看Token是否过期
     * @param token
     * @return false 未过期，true 已过期
     */
    public static Boolean tokenExpired(String token) {
        try {
            Claims claims = Jwts.parser().setSigningKey(tokenSignKey).parseClaimsJws(token).getBody();
            Date expiration = claims.getExpiration();
            Date currentDate = new Date();
            return expiration.before(currentDate);
        } catch (ExpiredJwtException ex) {
            return true;
        } catch (Exception ex) {
            return true;
        }
    }
}
